<template>
  <div class="admin-dashboard">
    <div class="admin-header">
      <h1>动物乐园后台管理系统</h1>
      <div class="header-actions">
        <span class="welcome-text">欢迎管理员</span>
        <button @click="logout" class="logout-btn">退出登录</button>
      </div>
    </div>
    
    <div class="admin-layout">
      <aside class="sidebar">
        <nav class="admin-nav">
          <ul>
            <li>
              <router-link to="/admin/dashboard" class="nav-item" active-class="active">
                <span class="nav-icon">📊</span>
                <span class="nav-text">仪表盘</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/animals" class="nav-item" active-class="active">
                <span class="nav-icon">🐾</span>
                <span class="nav-text">动物管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/categories" class="nav-item" active-class="active">
                <span class="nav-icon">📂</span>
                <span class="nav-text">分类管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/users" class="nav-item" active-class="active">
                <span class="nav-icon">👥</span>
                <span class="nav-text">用户管理</span>
              </router-link>
            </li>
          </ul>
        </nav>
      </aside>
      
      <main class="main-content">
        <div class="page-header">
          <h2>分类管理</h2>
          <button @click="showAddCategoryForm = true" class="add-btn">
            <span>+</span> 添加分类
          </button>
        </div>
        
        <div class="search-filter">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="搜索分类名称..."
            class="search-input"
          />
        </div>
        
        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>分类名称</th>
                <th>动物数量</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="category in filteredCategories" :key="category.id">
                <td>{{ category.id }}</td>
                <td>{{ category.name }}</td>
                <td>{{ getAnimalCountByCategory(category.id) }}</td>
                <td>{{ formatDate(category.createdAt) }}</td>
                <td>
                  <div class="action-buttons">
                    <button @click="editCategory(category)" class="edit-btn">编辑</button>
                    <button 
                      @click="deleteCategory(category.id)" 
                      class="delete-btn"
                      :disabled="getAnimalCountByCategory(category.id) > 0"
                    >
                      删除
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- 添加/编辑分类模态框 -->
        <div v-if="showAddCategoryForm || showEditForm" class="modal-overlay" @click="closeModal">
          <div class="modal-content" @click.stop>
            <div class="modal-header">
              <h3>{{ showEditForm ? '编辑分类' : '添加分类' }}</h3>
              <button @click="closeModal" class="close-btn">×</button>
            </div>
            <div class="modal-body">
              <form @submit.prevent="submitForm">
                <div class="form-group">
                  <label for="name">分类名称</label>
                  <input 
                    type="text" 
                    id="name" 
                    v-model="formData.name"
                    required
                    class="form-input"
                  />
                </div>
                <div class="form-group">
                  <label for="description">分类描述（可选）</label>
                  <textarea 
                    id="description" 
                    v-model="formData.description"
                    rows="3"
                    class="form-input"
                    placeholder="输入分类的简要描述..."
                  ></textarea>
                </div>
                <div class="form-actions">
                  <button type="button" @click="closeModal" class="cancel-btn">取消</button>
                  <button type="submit" class="submit-btn">
                    {{ showEditForm ? '更新' : '添加' }}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CategoryManagementView',
  data() {
    return {
      categories: [],
      animals: [],
      searchQuery: '',
      showAddCategoryForm: false,
      showEditForm: false,
      formData: {
        name: '',
        description: ''
      },
      editingCategoryId: null
    }
  },
  computed: {
    filteredCategories() {
      if (!this.searchQuery) return this.categories
      
      const query = this.searchQuery.toLowerCase()
      return this.categories.filter(category => 
        category.name.toLowerCase().includes(query)
      )
    }
  },
  mounted() {
    this.fetchCategories()
    this.fetchAnimals()
  },
  methods: {
    fetchCategories() {
      // 模拟数据，实际应该从API获取
      this.categories = [
        { id: 1, name: '食肉目', description: '包括狮子、老虎等大型猫科动物', createdAt: '2023-01-10' },
        { id: 2, name: '长鼻目', description: '包括大象等长鼻子哺乳动物', createdAt: '2023-01-12' },
        { id: 3, name: '奇蹄目', description: '包括马、犀牛等哺乳动物', createdAt: '2023-01-15' },
        { id: 4, name: '偶蹄目', description: '包括长颈鹿、鹿等哺乳动物', createdAt: '2023-01-18' },
        { id: 5, name: '灵长目', description: '包括猴子、猩猩等高等哺乳动物', createdAt: '2023-01-20' }
      ]
    },
    fetchAnimals() {
      // 模拟数据，实际应该从API获取
      this.animals = [
        { id: 1, name: '狮子', categoryId: 1 },
        { id: 2, name: '老虎', categoryId: 1 },
        { id: 3, name: '大象', categoryId: 2 },
        { id: 4, name: '长颈鹿', categoryId: 4 },
        { id: 5, name: '熊猫', categoryId: 1 }
      ]
    },
    getAnimalCountByCategory(categoryId) {
      return this.animals.filter(animal => animal.categoryId === categoryId).length
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString()
    },
    editCategory(category) {
      this.formData = {
        name: category.name,
        description: category.description || ''
      }
      this.editingCategoryId = category.id
      this.showEditForm = true
    },
    deleteCategory(id) {
      const animalCount = this.getAnimalCountByCategory(id)
      if (animalCount > 0) {
        alert('该分类下还有动物，无法删除！请先将动物移至其他分类或删除动物。')
        return
      }
      
      if (confirm('确定要删除这个分类吗？')) {
        // 实际应该调用API删除
        this.categories = this.categories.filter(category => category.id !== id)
      }
    },
    submitForm() {
      if (this.showEditForm) {
        // 编辑模式
        const index = this.categories.findIndex(c => c.id === this.editingCategoryId)
        if (index !== -1) {
          this.categories[index] = {
            ...this.categories[index],
            ...this.formData
          }
        }
      } else {
        // 添加模式
        const newCategory = {
          id: this.categories.length + 1,
          ...this.formData,
          createdAt: new Date().toISOString()
        }
        this.categories.push(newCategory)
      }
      this.closeModal()
    },
    closeModal() {
      this.showAddCategoryForm = false
      this.showEditForm = false
      this.editingCategoryId = null
      this.resetForm()
    },
    resetForm() {
      this.formData = {
        name: '',
        description: ''
      }
    },
    logout() {
      localStorage.removeItem('user')
      this.$router.push('/login')
    }
  }
}
</script>

<style scoped>
/* 复用AnimalManagementView.vue的大部分样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.add-btn {
  background-color: #27ae60;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: background-color 0.2s;
}

.add-btn:hover {
  background-color: #229954;
}

.search-filter {
  margin-bottom: 1.5rem;
}

.search-input {
  width: 100%;
  max-width: 400px;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #2c3e50;
}

.data-table tbody tr:hover {
  background-color: #f8f9fa;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}

.edit-btn,
.delete-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.edit-btn {
  background-color: #3498db;
  color: white;
}

.edit-btn:hover {
  background-color: #2980b9;
}

.delete-btn {
  background-color: #e74c3c;
  color: white;
}

.delete-btn:hover:not(:disabled) {
  background-color: #c0392b;
}

.delete-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
  opacity: 0.6;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: #f8f9fa;
}

.modal-body {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #2c3e50;
}

.form-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}

.cancel-btn,
.submit-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background-color: #5a6268;
}

.submit-btn {
  background-color: #28a745;
  color: white;
}

.submit-btn:hover {
  background-color: #218838;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .search-input {
    max-width: none;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>